import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login'
import mainPage from '@/components/mainPage'
import Register from '@/components/Register'
import test from '@/components/test'
import Cet4 from '@/components/person/cet4'
import Cet6 from '@/components/person/cet6'
import store from '../store'
import Cinema from '@/components/content/cinema'
import Fiction from '@/components/content/fiction'
import Magazine from '@/components/content/magazine'
import Recommend from '@/components/content/recommend'
import readMagazine from '@/components/content/readMagazine'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'mainPage',
      component: mainPage
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/cinema',
      name: 'cinema',
      component: Cinema
    },
    {
      path: '/fiction',
      name: 'fiction',
      component: Fiction
    },
    {
      path: '/magazine',
      name: 'magazine',
      component: Magazine
    },
    {
      path: '/recommend',
      name: 'recommend',
      component: Recommend
    },
    {
      path: '/test',
      name: 'test',
      component: test,
      children:[
        { path: '/cet4Word', component: Cet4 },
        { path: '/cet6Word', component: Cet6 }
      ]
    },
    {
      path: '/readMagazine',
      name: 'readMagazine',
      component: readMagazine
    }
  ]
})
//页面刷新时，如果token存在于localStorage中，那么就重新赋予token值
if (window.localStorage.getItem('token')) {
	store.commit('login', window.localStorage.getItem('token'));
}
// 添加一个导航守卫，对登录状态进行验证
router.beforeEach((to, from, next) => {
  console.log(to);
	if (to.path == '/test') {
		console.log('需要登录验证')  // 判断该路由是否需要登录权限
		if (store.state.token) {  // 通过vuex state获取当前的token是否存在
			next();
		}
		else {
      alert('您还未登录')
			next({
				path: '/Login',
				query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
			})
		}
	}
	else {
		next();
	}
  })

export default router;
